#!/bin/bash

###############################################
# Web 应用自动部署脚本
# 功能：备份、部署、健康检查、回滚
###############################################

set -e  # 遇到错误立即退出

# 配置变量
APP_NAME="web-app"
DEPLOY_DIR="/var/www/html/${APP_NAME}"
BACKUP_DIR="/var/www/backup"
NGINX_CONF="/etc/nginx/conf.d/${APP_NAME}.conf"
HEALTH_CHECK_URL="http://localhost:8082"

# 颜色输出
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}   开始部署 ${APP_NAME}${NC}"
echo -e "${GREEN}========================================${NC}"

# 1. 创建必要的目录
echo -e "${YELLOW}[1/7] 创建目录...${NC}"
mkdir -p ${DEPLOY_DIR}
mkdir -p ${BACKUP_DIR}

# 2. 备份旧版本
echo -e "${YELLOW}[2/7] 备份旧版本...${NC}"
if [ -d "${DEPLOY_DIR}" ] && [ "$(ls -A ${DEPLOY_DIR})" ]; then
    BACKUP_NAME="${APP_NAME}_$(date +%Y%m%d_%H%M%S)"
    tar -czf ${BACKUP_DIR}/${BACKUP_NAME}.tar.gz -C ${DEPLOY_DIR} . 2>/dev/null || true
    echo -e "${GREEN}✅ 备份完成: ${BACKUP_NAME}.tar.gz${NC}"
else
    echo -e "${YELLOW}⚠️  没有旧版本，跳过备份${NC}"
fi

# 3. 部署新版本
echo -e "${YELLOW}[3/7] 部署新版本...${NC}"
cp -r ${WORKSPACE}/* ${DEPLOY_DIR}/
echo -e "${GREEN}✅ 文件部署完成${NC}"

# 4. 配置 Nginx
echo -e "${YELLOW}[4/7] 配置 Nginx...${NC}"
cat > ${NGINX_CONF} <<EOF
server {
    listen 8082;
    server_name _;

    root ${DEPLOY_DIR};
    index index.html;

    location / {
        try_files \$uri \$uri/ =404;
    }

    # 健康检查端点
    location /health {
        access_log off;
        return 200 "OK";
        add_header Content-Type text/plain;
    }
}
EOF
echo -e "${GREEN}✅ Nginx 配置完成${NC}"

# 5. 检查 Nginx 配置（如果 nginx 命令可用）
echo -e "${YELLOW}[5/7] 检查 Nginx 配置...${NC}"
if command -v nginx &> /dev/null; then
    nginx -t
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✅ Nginx 配置检查通过${NC}"
    else
        echo -e "${RED}❌ Nginx 配置错误，开始回滚...${NC}"
        exit 1
    fi
else
    echo -e "${YELLOW}⚠️  nginx 命令不可用（容器环境），跳过配置检查${NC}"
    echo -e "${YELLOW}⚠️  请在宿主机手动执行: nginx -t && systemctl reload nginx${NC}"
fi

# 6. 重载 Nginx（如果 systemctl 可用）
echo -e "${YELLOW}[6/7] 重载 Nginx...${NC}"
if command -v systemctl &> /dev/null; then
    systemctl reload nginx || systemctl restart nginx
    sleep 2
    echo -e "${GREEN}✅ Nginx 重载完成${NC}"
else
    echo -e "${YELLOW}⚠️  systemctl 不可用（容器环境），跳过 Nginx 重载${NC}"
    echo -e "${YELLOW}⚠️  请在宿主机手动执行: systemctl reload nginx${NC}"
fi

# 7. 健康检查
echo -e "${YELLOW}[7/7] 健康检查...${NC}"
MAX_RETRY=5
RETRY=0

while [ $RETRY -lt $MAX_RETRY ]; do
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" ${HEALTH_CHECK_URL}/health || echo "000")

    if [ "$HTTP_CODE" == "200" ]; then
        echo -e "${GREEN}✅ 健康检查通过！应用已成功部署${NC}"
        echo -e "${GREEN}🌐 访问地址: http://192.168.233.168:8082${NC}"
        exit 0
    fi

    RETRY=$((RETRY+1))
    echo -e "${YELLOW}⏳ 第 ${RETRY}/${MAX_RETRY} 次健康检查失败，等待重试...${NC}"
    sleep 3
done

# 健康检查失败，执行回滚
echo -e "${RED}❌ 健康检查失败！开始回滚...${NC}"

# 查找最新的备份
LATEST_BACKUP=$(ls -t ${BACKUP_DIR}/${APP_NAME}_*.tar.gz 2>/dev/null | head -1)

if [ -n "$LATEST_BACKUP" ]; then
    echo -e "${YELLOW}🔙 回滚到: $(basename $LATEST_BACKUP)${NC}"
    rm -rf ${DEPLOY_DIR}/*
    tar -xzf ${LATEST_BACKUP} -C ${DEPLOY_DIR}

    # 容器环境检测
    if command -v systemctl &> /dev/null; then
        systemctl reload nginx
    else
        echo -e "${YELLOW}⚠️  systemctl 不可用（容器环境），请在宿主机手动执行: systemctl reload nginx${NC}"
    fi

    echo -e "${GREEN}✅ 回滚完成${NC}"
else
    echo -e "${RED}❌ 未找到备份文件，无法回滚${NC}"
fi

exit 1
